package samplebasic
import sweet.mvc.api._
import sweet.helper._  
class GuessGameController extends Controller {
  val minNum = 1
  val maxNum = 10
  
	handle("/index"){ View("redirect:/guess") }
  
	handleReq("/guess"){ req =>
    req.method match {
      case Get =>{ 
        val sess = req.sess
        if(sess.attr("game")==None || req.param("restart", "false").toBoolean){ 
          val toBeGuessNum = Rand.randInt(minNum, maxNum+1)
          val game = new GuessGame(minNum, maxNum, toBeGuessNum, 0)
          logger.debug("New user session started with New Game: toBeGuessNum="+toBeGuessNum) 
          sess("game") = game
        }    
        View("/index") 
      }
      case Post =>{
        val guessedNumStr = req("guessgame.number")
        if(guessedNumStr.length < minNum || guessedNumStr.length > maxNum){
          View("/index", "error"-> "Input is out of range. Guess again.")
        }else if(!guessedNumStr.forall(c=> java.lang.Character.isDigit(c))){
          View("/index", "error"-> "Invalid number. Guess again.")
        }else{
          val guessedNum = guessedNumStr.toInt
          val sess = req.sess
          val game = sess("game").asInstanceOf[GuessGame]
          val toBeGuessNum = game.toBeGuessNum
          
          //update guess count.
          game.guessCount += 1
          
          logger.debug("Gussed num "+guessedNum)
          logger.debug("To be guessed num "+toBeGuessNum)
          
          if(toBeGuessNum == guessedNum){
            sess.remove("game")
            View("/winner", "guessCount"->game.guessCount)
          }else{
            val error =                     
              if(toBeGuessNum > guessedNum) "It's too small. Guess again."
              else "It's too big. Guess again."
            View("/index", "error"->error)
          }
        }
      }
    }
  }
  
  class GuessGame(val minNum: Int, val maxNum: Int, val toBeGuessNum: Int, var guessCount: Int)
}

